package com.andy.infrastructure.util;

import com.andy.infrastructure.ioc.annotation.Autowire;
import com.andy.infrastructure.ioc.annotation.Component;

import java.sql.SQLException;

/**
 * 事务管理器类：负责手动事务的开启、提交、回滚
 */
@Component
public class TransactionManager {

    @Autowire
    private CurrentThreadConnectionManager connectionUtils;


    // 开启手动事务控制
    public void beginTransaction() throws SQLException {
        connectionUtils.getCurrentThreadConn().setAutoCommit(false);
    }

    // 是否当前已经开启了事物
    public boolean isTransactionBegan() throws SQLException {
        return !connectionUtils.getCurrentThreadConn().getAutoCommit();
    }

    // 关闭事物
    public void closeTransaction() throws SQLException {
        connectionUtils.getCurrentThreadConn().setAutoCommit(true);
    }


    // 提交事务
    public void commit() throws SQLException {
        connectionUtils.getCurrentThreadConn().commit();
    }


    // 回滚事务
    public void rollback() throws SQLException {
        connectionUtils.getCurrentThreadConn().rollback();
    }
}
